<?php

ini_set('include_path',($customDir = ($innerDir = dirname(__FILE__).'/').'../custom_oo/').':'.($defaultDir = ($innerDir.'default_oo/').':'.ini_get('include_path')));

require_once('classes/httpExceptions.php');

try{
    function ob_renderer($caughtOutput){
        return $caughtOutput;
    }ob_start('ob_renderer');

    require_once('classes/RequestInterpreterFactory.class.php');

    if (file_exists($innerDir.'../config.php')){
        $interpreter = RequestInterpreterFactory::getInterpreterFromPhp($innerDir.'../config.php');
    }elseif(file_exists($innerDir.'../config.xml')){
        $interpreter = RequestInterpreterFactory::getInterpreterFromXml($innerDir.'../config.xml');
    }else{
        throw new Exception('No config file found, this should exist as either "config.php" or "config.xml" as a sibling to __core__');
    }

    $uri = $_SERVER['REQUEST_URI'];
    if (($pos = strpos($uri,'?')) !== false){
        $uri = substr($uri,0,$pos);
    }

    if ($interpreter->hasMatch($uri)){
        $interpreter->runMatch();
    }else{
        throw new Http404Exception();
    }

    ob_end_flush();
    
}catch(Exception $e){ // doing everything manually as it's more reliable at this stage
    ob_clean();
    include_once('classes/SimpleModel.class.php');
    if ($e instanceof HttpException){
        header($e->getHeader());
        $model = new SimpleModel(array('error.status.code' => $e->getStatusCode(), 'error.internal.code' => 'generic.uncaught.http-'.$e->getStatusCode().'.exception', 'error.exception.object' => $e, 'error.catchcontext.explination' => $e->getUserText()));
    }else{
        header($_SERVER['SERVER_PROTOCOL'].' 500 Internal Server Error');
        $model = new SimpleModel(array('error.status.code' => 500, 'error.internal.code' => 'generic.uncaught.exception', 'error.exception.object' => $e, 'error.catchcontext.explination' => 'Experienced an unrecoverable error. Please try again later. <pre>Reason: '.$e->getMessage().'</pre>'));
    }
    $errorPageDir = $innerDir.'/../error_pages/';
    if (file_exists($fileToLoad = $errorPageDir.$model->get('error.status.code').'.php')){
        include($fileToLoad);
    }elseif (file_exists($fileToLoad = $errorPageDir.'error.php')){
        include($fileToLoad);
    }else{
        print $model->get('error.catchcontext.explination');
    }
    ob_end_flush();
}

?>